﻿namespace Softserve.Pottery.Infrastructure
{
    using System;
    using Softserve.Pottery.Infrastructure.Interfaces;

    /// <summary>
    /// Provides basic functionality of domain logic controller
    /// </summary>
    public abstract class DomainControllerBase : IDisposable
    {
        protected DomainControllerBase(IRepository context) : this(context, null, null) { }

        protected DomainControllerBase(IRepository context, IMessenger bridge) : this(context, bridge, null) { }

        protected DomainControllerBase(IRepository context, IMessenger bridge , IServiceProvider provider) 
        {
            m_Repository = context;       
            m_Bridge = bridge;
            m_ServiceLocator = provider;
            m_IsDIContext = context is IRepository;
        }


        public IRepository Storage { get { return m_Repository; } }

        public IMessenger Messager { get { return m_Bridge; } }
        
        #region IDisposable members

        protected abstract void Dispose(bool disposeManaged);

        public void Dispose()
        {
            Dispose(true);

            ///utilize storage code
            if (m_Repository != null & !m_IsDIContext)
            {
                m_Repository.Dispose();
            }

            GC.SuppressFinalize(this);
        }

        #endregion

        ~DomainControllerBase()
        {
            Dispose(false);
        }

        #region Private fields
        
        private readonly bool m_IsExternal = false;

        private readonly bool m_IsDIContext = false;

        private readonly IRepository m_Repository = null;

        private readonly IServiceProvider m_ServiceLocator = null;

        private readonly IMessenger m_Bridge = null;

        #endregion
    }
}
